const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const ELEMENT_NUMBER = 10;

// 查询用户已报名的活动
module.exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const openID = wxContext.OPENID;
  const tableNumber = event.tableNumber || 1;
  
  // 先在 Group_Registration_Information 中按报名时间倒序分页查询用户的分组报名记录
  const regRes = await db.collection('Group_Registration_Information')
    .where({ OpenID: openID })
    .orderBy('RegistrationTime', 'desc')
    .skip((tableNumber - 1) * ELEMENT_NUMBER)
    .limit(ELEMENT_NUMBER)
    .get();

  const regs = regRes.data || [];
  if (regs.length === 0) {
    return { activities: [] };
  }

  // 按报名记录顺序映射到 activityID（通过查 group 表），并去重（按首次出现顺序）
  const groupIDs = regs.map(r => r.GroupID).filter(Boolean);
  const groupsRes = await db.collection('Activity_Group_Information')
    .where({ _id: db.command.in(groupIDs) })
    .get();
  const groupMap = {};
  (groupsRes.data || []).forEach(g => { groupMap[g._id] = g; });

  const orderedActivityIDs = [];
  const seen = new Set();
  for (const r of regs) {
    const g = groupMap[r.GroupID];
    const aid = g && g.ActivityID;
    if (aid && !seen.has(aid)) {
      seen.add(aid);
      orderedActivityIDs.push(aid);
    }
  }

  if (orderedActivityIDs.length === 0) {
    return { activities: [] };
  }

  // 查询活动信息
  const actRes = await db.collection('Activity_Information')
    .where({ _id: db.command.in(orderedActivityIDs) })
    .get();
  const idToActivity = {};
  (actRes.data || []).forEach(item => { idToActivity[item._id] = item; });

  // 按报名顺序构建返回的活动列表
  const activities = [];
  for (const aid of orderedActivityIDs) {
    const item = idToActivity[aid];
    if (!item) continue;
    // 查询该活动的分组时间列表
    const groupRes = await db.collection('Activity_Group_Information')
      .where({ ActivityID: item._id })
      .orderBy('GroupStartTime', 'asc')
      .get();
    activities.push({
      activityID: item._id,
      activityName: item.ActivityName,
      activityImage: item.ActivityImageURL,
      activityStartTime: (groupRes.data || []).map(g => g.GroupStartTime),
      activityLocation: item.ActivityLocation
    });
  }

  return { activities };
};
